﻿using Hsp.Media.Model.Models;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Hsp.Media.App.Utility
{
    /// <summary>
    /// 字幕文件解析帮助类
    /// </summary>
    public class SrtHelper
    {
        //定义一个ModelList的列表用于接受从文件读取的内容
        private static List<MediaSubtitleContent>? contentList;

        public static void GetSrt(int? fileId, SqlSugarClient db, string srt)
        {
            Encoding encoding = Encoding.Default;
            //encoding = FileEncoding.GetType(srt);
            //using (FileStream fs = new(srt, FileMode.Open))
            //{
            //    encoding = FileEncoding.GetType(fs);
            //}

            //encoding = Encoding.GetEncoding("gbk");
            //encoding = Encoding.GetEncoding("gb2312");
            //Console.WriteLine(encoding);

            var file = db.Queryable<MediaSubtitleFile>().First(f => f.Id == fileId);
            if (file == null) return;
            encoding = Encoding.GetEncoding(file?.FileEncoding ?? "GBK");

            List<MediaSubtitleContent> contents = SrtHelper.ParseSrt(file?.Id, srt, file?.TypeId, encoding);
            foreach (var content in contents)
            {
                Console.WriteLine(content.Seq);
                Console.WriteLine(SrtHelper.GetTimeString(content));
                if (file?.TypeId == 0) Console.WriteLine(content.Chinese);
                if (file?.TypeId == 1) Console.WriteLine(content.English);
                if (file?.TypeId == 2)
                {
                    Console.WriteLine(content.Chinese);
                    Console.WriteLine(content.English);
                }

                Console.WriteLine("");
            }

            db.Deleteable<MediaSubtitleContent>().Where(c=>c.FileId == fileId).ExecuteCommand();
            db.Insertable(contents).ExecuteCommand();

            //输出系统默认非Unicode编码
            //Console.WriteLine(Encoding.Default.EncodingName);
            //使用系统默认非Unicode编码来打开文件
            //var fileContent = File.ReadAllText(srt, encoding);
            //Console.WriteLine(fileContent);
        }

        //定义一个获取当前时间显示的string的方法
        public static string? GetTimeString(MediaSubtitleContent content)
        {
            string? currentTimeTxt;
            if (content.EndTime != null)
            {
                currentTimeTxt = DateTime.Parse(content?.StartTime?.ToString()).ToString("HH:mm:ss,fff")
                    + " --> "
                    + DateTime.Parse(content?.EndTime?.ToString()).ToString("HH:mm:ss,fff");
            }
            else
            {
                currentTimeTxt = DateTime.Parse(content?.StartTime?.ToString()).ToString("HH:mm:ss,fff");
            }
            return currentTimeTxt;
        }

        //读取文件中的内容到contentList列表
        public static List<MediaSubtitleContent> ParseSrt(int? fileId, string srtPath, int? type, Encoding encoding)
        {
            contentList = new List<MediaSubtitleContent>();
            string line;
            using (FileStream fs = new(srtPath, FileMode.Open))
            {
                using StreamReader sr = new(fs, encoding);
                StringBuilder sb = new();
                while ((line = sr?.ReadLine()) != null)
                {

                    if (!line.Equals(""))
                    {
                        sb.Append(line).Append("@");
                        continue;
                    }

                    string[] parseStrs = sb.ToString().Split('@');
                    if (parseStrs.Length < 3)
                    {
                        sb.Remove(0, sb.Length);// 清空，否则影响下一个字幕元素的解析</i>  
                        continue;
                    }

                    MediaSubtitleContent srt = new();
                    srt.FileId = fileId;
                    srt.Seq = int.Parse(parseStrs[0].ToString());
                    string strTime = parseStrs[1];
                    var timeMile = strTime.Replace(" --> ", "*").Replace(",", ".").Split('*');
                    srt.StartTime = TimeSpan.Parse(timeMile[0]);
                    srt.EndTime = timeMile.Length > 1 ? TimeSpan.Parse(timeMile[1]) : null;

                    if (type == 2)
                    {
                        var chinese = string.Empty;
                        var english = string.Empty;
                        for (int i = 2; i < parseStrs.Length; i++)
                        {
                            var str = parseStrs[i];
                            var isEnglish = IsEnglish(str);
                            var isChinese = IsChinese(str);


                            if (IsEnglish(str))
                            {
                                english += str;
                            }
                            else
                            {
                                chinese += str;
                            }
                        }
                        srt.Chinese = chinese;
                        srt.English = english;
                    }
                    else
                    {
                        string strBody = string.Empty;
                        for (int i = 2; i < parseStrs.Length; i++)
                        {
                            strBody += parseStrs[i];
                        }
                        if (type == 0)
                        {
                            srt.Chinese = strBody;
                        }
                        else
                        {
                            srt.English = strBody;
                        }

                    }

                    contentList.Add(srt);
                    sb.Remove(0, sb.Length);
                }

            }
            return contentList;
        }

        //截取冲击式样形状
        private static bool IsEnglish(string s)
        {
            Match mInfo = Regex.Match(s, @"^[A-Za-z0-9;:'!…\-,.? ]+$");
            if (mInfo.Success) //如果是英文
                return true;
            else
                return false;
        }

        private static bool IsChinese(string s)
        {
            byte[] byte_len = System.Text.Encoding.Default.GetBytes(s);
            if (byte_len.Length == 2) { return true; }

            return false;
        }

    }
}
